package com.example.demo.controller;

import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        String userType = request.get("userType");

        Map<String, Object> result = userService.register(username, password, userType);
        if (Boolean.TRUE.equals(result.get("success"))) {
            // 注册成功后自动登录
            Map<String, Object> loginResult = userService.login(username, password, userType);
            if (Boolean.TRUE.equals(loginResult.get("success"))) {
                loginResult.put("welcome", "欢迎注册，已自动登录！");
                return ResponseEntity.ok(loginResult);
            } else {
                // 登录失败
                return ResponseEntity.ok(result);
            }
        } else {
            // 注册失败
            return ResponseEntity.ok(result);
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> request) {
        String username = request.get("username");
        String password = request.get("password");
        String userType = request.get("userType");

        Map<String, Object> result = userService.login(username, password, userType);
        return ResponseEntity.ok(result);
    }
} 